package nio.demo;

import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Desc:   ServerSocketChannel 案例
 *
 * @author: cww
 * @DateTime: 2020-02-04 9:45
 */

public class ServerSocketChannelDemo {
    /**
     * 阻塞模式案例
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception{
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(9999));

        // 通常不会仅仅只监听一个连接,在while循环中调用 accept()方法
        while (true) {
            // 接收到新进的连接请求，accept()方法会一直阻塞到有新连接到达
            SocketChannel socketChannel = serverSocketChannel.accept();

            // 关闭 ServerSocketChannel 此处仅做示例关闭，实际流程一般不会在此关闭
            serverSocketChannel.close();
        }
    }

    /**
     * 非阻塞模式 ServerSocketChannel
     */
    public void nonBlokingServerSocket() throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(9999));
        serverSocketChannel.configureBlocking(false);

        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel != null) {
                // 如果收到新进请求则可以执行相应业务，如果未收到，则可以去处理其他业务
            }
        }
    }
}
